package com.rt.cloud.auth.controller;

import com.rt.easyjava.common.base.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/oauth")
public class OauthController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/myToken")
    public Map<String, Object> getAccessToken(@RequestParam Map<String, String> parameters, HttpServletRequest request) {
        return getToken(parameters, request);
    }

    @PostMapping("/myToken")
    public Map<String, Object> postAccessToken(@RequestParam Map<String, String> parameters, HttpServletRequest request) {
        return getToken(parameters, request);
    }

    private Map<String, Object> getToken(Map<String, String> parameters, HttpServletRequest request){
        // 取当前服务端口
        String path = "http://127.0.0.1:"+request.getServerPort();
        RestTemplate restTemplate = new RestTemplate();
        String url = path+"/core/oauth/token";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
        map.add("username", parameters.get("username"));
        map.add("password", parameters.get("password"));
        map.add("grant_type", "password");
        map.add("client_id", "mengxuegu-pc");
        map.add("client_secret", "mengxuegu-secret");

        HttpEntity<MultiValueMap<String, String>> request1 = new HttpEntity<>(map, headers);
        Result result = restTemplate.postForObject(url, request1, Result.class);
        return result.getMap();
    }

}
